﻿using System.Web;
using System.Web.UI;

namespace CodeAffinity.FormAbstraction
{
    public class DataObjectLoader : IVisitor
    {
        private FormObjectDataInterchange DataInterchange { get; set; }

        private DataClassBase DataObject { get; set; }

        private DataObjectPage Page { get; set; }

        private LoadMementos LoadState
        {
            get { return (LoadMementos)HttpContext.Current.Session["loadstate"]; }
            set { HttpContext.Current.Session["loadstate"] = value; }
        }

        public DataObjectLoader()
        {
            DataInterchange = new FormObjectDataInterchange();
            LoadState = new LoadMementos();
        }

        #region IVisitor Members

        public IVisitedElement Visited { get; set; }

        public void Visit(IVisitedElement element)
        {
            if (element is DataObjectPage)
                Visited = element;
            else
                throw new InvalidVisit(element, this);

            Page = (DataObjectPage)Visited;

            SaveLoadState();

            DataInterchange.ObjectToForm(Page);
        }

        #endregion

        private void SaveLoadState()
        {
            for (int i = 0; i < Page.Session.Count; i++)
                if (Page.Session[i] is DataClassBase)
                {
                    DataClassBase dataObj = (DataClassBase)Page.Session[i];
                    DataClassBase clone = (DataClassBase)dataObj.Clone();
                    LoadState.Add(clone);
                }
        }


    }
}
